package com.gezi.admin.config.validate.constraint.enumvalid;

import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @Author 格子代码
 * @createDate 2024/2/10 09:00
 * @contact 1424529270@qq.com
 **/
@Slf4j
public class EnumValidator implements ConstraintValidator<EnumValid, Object> {

    private EnumValid annotation;

    @Override
    public void initialize(EnumValid constraintAnnotation) {
        annotation = constraintAnnotation;
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
        Class<?> cls = annotation.target();
        boolean ignoreEmpty = annotation.isNotEmpty();
        // target为枚举，并且value有值，或者不忽视空值，才进行校验
        if (cls.isEnum() && !ignoreEmpty) {
            return true;
        }
        boolean isCheck = cls.isEnum() && null != value;
        if (!isCheck) {
            return false;
        }
        boolean result = false;

        try {
            if(value instanceof Enum){
                //获取枚举
                Enum eValue = (Enum) value;
                Object[] enums = cls.getEnumConstants();
                for (Object obj : enums) {
                    if(obj == eValue){
                        return true;
                    }
                }
            }else if(value instanceof String){
                //获取枚举
                String eValue = (String) value;
                Object[] enums = cls.getEnumConstants();
                for (Object obj : enums) {
                    Enum eObj = (Enum) obj;
                    if(eObj.name().equals(eValue)){
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            log.error("EnumValidator call isValid() method exception", e);
        }
        return result;
    }
}
